﻿
namespace MinesV1
{
	static public class MinesSolver
	{
		private static int _numLinesBoard;
        private static int _numColumnsBoard;
        private static int _numLinesBoardExtended;
        private static int _numColumnsBoardExtended;
		
		internal static string[] MineSearch(string[] stringInput)
		{
            var minesBoard = CreateBooleanBoard(stringInput);
            var playBoard = CreatePlayBoard(minesBoard);
			return PlayBoardToString(playBoard);
		}

        internal static int[,] CreateBooleanBoard(string[] s)
        {
            _numLinesBoard = s.Length;
            _numColumnsBoard = s[0].Length;
            _numLinesBoardExtended = _numLinesBoard + 2;
            _numColumnsBoardExtended = _numColumnsBoard + 2;

            var minesBoard = new int[_numLinesBoardExtended, _numColumnsBoardExtended];
            
            var i = 1;
            foreach (var line in s)
            {   
                var j = 1;
                foreach (var element in line)
                {
                    if (element == '*') minesBoard[i, j] = 1;
                    j++;
                }
                i++;
            }
            return minesBoard;
        }

        internal static int[,] CreatePlayBoard(int[,] minesBoard)
		{
            var playBoard = new int[_numLinesBoardExtended, _numColumnsBoardExtended];

            for (var i = 1; i < _numLinesBoard + 1; i++)
			{
                for (var j = 1; j < _numColumnsBoard + 1; j++)
			        if (minesBoard[i, j] == 1)
			            UpdatePlayBoard(playBoard, i, j);
			}
			return playBoard;
         }

        private static int[,] UpdatePlayBoard(int[,] playBoard, int i, int j)
        {
            playBoard[i - 1, j - 1] += 1;
            playBoard[i - 1, j]     += 1;
            playBoard[i - 1, j + 1] += 1;
            playBoard[i, j + 1]     += 1;
            playBoard[i, j - 1]     += 1;
            playBoard[i + 1, j - 1] += 1;
            playBoard[i + 1, j]     += 1;
            playBoard[i + 1, j + 1] += 1;

            return playBoard;
        }

        internal static string[] PlayBoardToString(int[,] playBoard)
		{
		    var strOutput = new string[_numLinesBoard];

            for (var i = 1; i < _numLinesBoardExtended - 1; i++)
            {
                var strOutputLine = "";

                for (var j = 1; j < _numColumnsBoardExtended - 1; j++)
                {
                    strOutputLine += playBoard[i, j].ToString();
                }
                strOutput[i - 1] = strOutputLine;
            }
            return strOutput;
		}
	}
}
